/*
 *@(#)AuthenticationFilter.java 1.0 Mar 16, 2008
 *Copyright Fution Bai
 *
 */
package codebush.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author Fution Bai
 * @since 1.0
 */
public class AuthenticationFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession();
		if (session.getAttribute("userName") == null) {
			Cookie[] cookie = httpRequest.getCookies();
			String userId = null, email = null, name = null;
			int i = 0;
			while (cookie != null && i < cookie.length) {
				if (cookie[i].getName().equals("userId")) {
					userId = cookie[i].getValue();
				}
				if (cookie[i].getName().equals("email")) {
					email = cookie[i].getValue();
				}
				if (cookie[i].getName().equals("userName")) {
					name = cookie[i].getValue();
				}
				if (userId != null && email != null && name != null) {
					session.setAttribute("userId", userId);
					session.setAttribute("email", email);
					session.setAttribute("userName", name);
					break;
				}
				i++;
			}
		}
		filterChain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
